Database Mail is a solution that enables you to send
email messages from SQL Server. It is disabled by default and uses the
SMTP standard to deliver messages, so there is no need to have a MAPI
client such as Outlook installed on the server.
It
runs as an isolated process outside of SQL Server to ensure it doesn’t
affect the availability of your database, it can be configured with
multiple SMTP servers for redundancy, and is fully supported to run on
a Windows failover cluster.
Database
Mail uses SQL Server Service Broker to provide asynchronous message
delivery, and you must be a member of the DatabaseMailUserRole in msdb
to be able to send email messages. It is not supported in SQL Server
Express.
Scenarios where Database Mail is often used include:
You can also send emails in HTML format.
Configuring Database Mail
Before
you configure Database Mail you’ll need to have access to an existing
SMTP server. Microsoft IIS, which comes with Windows, has an SMTP
service that you can configure easily if you don’t have an existing
SMTP server on your network.
The easiest way to configure Database Mail is by using the Configure Database Mail wizard accessible by right-clicking Database Mail under the Management section of a SQL Server that you have connected to in Management Studio.
You
also use the same wizard to manage the Database Mail configuration
after you’ve initially set up. When you run the wizard for the first
time, you’ll need to select Set up Database Mail by performing the following tasks:
Next you’ll need to specify a Profile
name and create new SMTP accounts through which to send emails. You can
add multiple SMTP accounts on different servers to a Profile. If the
first account fails then Database Mail will try the next account and
server in the list. In Figure 1
in the active window, you can see a second email account and SMTP
server being added to a Database Mail profile (seen in the inactive
window).
Once you’ve created a profile, the next screen will prompt you to configure profile security, where you can setup your profile to be Public and accessible to all users, or Private and accessible to a specific user.
The last screen allows you to configure parameters such as retry attempts, but generally you can just leave the defaults.
Once
you’ve run through the wizard you’ll now be able to use Database Mail
by calling the sp_send_dbmail stored procedure. Here is sample code
that sends a basic email to an address using the CompanySQLServers
profile that was created using the Database Mail wizard:
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'CompanySQLServers',
@recipients = '[email protected]',
@body = 'Output from procedure X was not as expected',
@subject = 'Procedure X execution';